package com.da.core.container;

import java.io.File;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.Deque;

public class ComponentScanner {
    public void scan(String basePackage, BeanHandler func) {
        Deque<String> stack = new ArrayDeque<>();
        stack.push(basePackage);
        while (!stack.isEmpty()) {
            String packageName = stack.pop();
            String basePath = packageName.replace(".", "/");
            URL url = Thread.currentThread().getContextClassLoader().getResource(basePath);
            if (url == null) {
                continue;
            }
            File baseDir = new File(url.getFile());
            File[] files = baseDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        stack.push(packageName + "." + file.getName());
                    } else if (file.getName().endsWith(".class")) {
                        String className = packageName + "." + file.getName().replace(".class", "");
                        try {
                            Class<?> clazz = Class.forName(className);
                            func.callback(clazz);
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }


}
